exports.handler = function(sid, query, callback) {
    var condition = {};


    var db = gServers.getGameDB(sid);
    if (!db) {
       callback('db eror'); return;
    }

    var dbUser = db.collection('user');
    var dbPay = db.collection('pay');
    var data = {};

    var begin = (new Date(query.start + " 00:00:00")).getStamp();
    var end = (new Date()).getStamp();
    for (var stamp = begin;stamp <= end;) {
        var t = Date.createFromStamp(stamp);
        var month = t.getFullYear()*100 + t.getMonth() + 1;
        data[month] = {"create":0, "login":0, "payUsers":{}, "payCash":0, "payAmt":0};
        stamp = Date.nextMonth(stamp);
    }

    async.series([
        function(cb) {
            var cursor = dbUser.find({}, {'mark.day':1, 'info.create':1});
            cursor.each(function(err, item) {
                if (err || cursor.isClosed()) {
                    cb(err); return;
                }
                
                var lastMonth = Math.floor(item.mark.day/100);
                var createTime = Date.createFromStamp(item.info.create);
                var createMonth = createTime.getFullYear()*100 + createTime.getMonth() + 1;
                data[createMonth].create++;
                for (var month = createMonth; month <= lastMonth; ) {
                    data[month].login++;
                    month += ((month%100 >= 12) ? 89 : 1);
                }
            });
        },
        function(cb) {
            var cursor = dbPay.find({}, {'openid':1, 'time':1, 'amt':1});
            cursor.each(function(err, item) {
                if (err || cursor.isClosed()) {
                    cb(err); return;
                }
                
                var time = new Date(item.time);
                var month = time.getFullYear()*100 + time.getMonth() + 1;
                var monthData = data[month];
                monthData.payUsers[item.openid] = 0;
                monthData.payAmt += +item.amt;
            });
        },
    ], function(err) {
        for (var month in data) {
            var item = data[month];
            console.log([sid, month, item.create, item.login, Object.keys(item.payUsers).length, item.payAmt].join('\t'));
        }
        callback(err); return;
    });;

}

exports.checkQuery = function(query) {
    var start = query.start;
    if (!start || start.length != 10) {
        return false;
    }
    return true;
}

exports.help = function() {
    return [
        "start=yyyy-MM-dd",
        "按月统计玩家注册留存",
    ];
}

exports.getTitle = function(query) {
    var title = ['sid', '月份', '注册', '活跃', '充值人数', '充值金额(未换算)'];
    console.log(title.join('\t'));
}
